#!/usr/bin/env python3
"""
分析解的路径长度分布，并生成直方图与统计表。

示例：
    python scripts/analyze_solutions.py outputs/backtrack_trace.json
"""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path
from typing import Dict, List

import matplotlib.pyplot as plt
import pandas as pd


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="解决方案路径长度分析",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument(
        "input",
        type=Path,
        help="backtrack_trace.json 文件路径",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=Path("outputs/analysis"),
        help="分析结果输出目录",
    )
    return parser.parse_args()


def load_solutions(path: Path) -> List[Dict]:
    with path.open("r", encoding="utf-8") as fh:
        data = json.load(fh)
    return data.get("solutions", [])


def plot_hist(lengths: List[int], output_dir: Path) -> None:
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.hist(lengths, bins=range(min(lengths), max(lengths) + 2), color="#55a868", edgecolor="#2b8a3e")
    ax.set_title("解的路径长度直方图")
    ax.set_xlabel("路径长度")
    ax.set_ylabel("出现次数")
    output_dir.mkdir(parents=True, exist_ok=True)
    out_path = output_dir / "solution_path_lengths.png"
    fig.tight_layout()
    fig.savefig(out_path, dpi=200)
    plt.close(fig)
    print(f"[analysis] 路径长度直方图保存于：{out_path}")


def save_table(lengths: List[int], output_dir: Path) -> None:
    counter = Counter(lengths)
    rows = [{"length": length, "count": count} for length, count in sorted(counter.items())]
    df = pd.DataFrame(rows)
    output_dir.mkdir(parents=True, exist_ok=True)
    out_path = output_dir / "solution_path_lengths.csv"
    df.to_csv(out_path, index=False)
    print(f"[analysis] 路径长度统计表保存于：{out_path}")


def main() -> None:
    args = parse_args()
    solutions = load_solutions(args.input)
    if not solutions:
        raise ValueError("未找到任何解，请确认输入文件是否正确。")

    lengths = []
    for solution in solutions:
        path = solution.get("path") or []
        if isinstance(path, list):
            lengths.append(len(path))

    if not lengths:
        raise ValueError("解的路径信息为空，无法统计。")

    plot_hist(lengths, args.output)
    save_table(lengths, args.output)


if __name__ == "__main__":
    main()